package com.woniuxy.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.woniuxy.entity.NormalOrder;
import com.woniuxy.entity.ReceivableOrder;
import com.woniuxy.entity.ReturnOrder;
import com.woniuxy.entity.Waybill;
import com.woniuxy.entity.dto.ReceivableOrderDTO;
import com.woniuxy.entity.dto.ReturnOrderDTO;
import com.woniuxy.mapper.ReceivableOrderMapper;
import com.woniuxy.mapper.ReturnOrderMapper;
import com.woniuxy.service.ReturnOrderService;
import com.woniuxy.util.PageData;
import com.woniuxy.util.ResponseData;
import com.woniuxy.util.SnowflakeIdGenerator;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class ReturnOrderServiceImpl implements ReturnOrderService {
    @Resource
    private ReturnOrderMapper returnOrderMapper;
    @Override
    public ResponseData<?> queryReturnOrder(PageData<ReturnOrderDTO> pageData) {
        PageHelper.startPage(pageData.getPageNum(),pageData.getPageSize());
        List<ReturnOrderDTO> returnOrderDTOS = returnOrderMapper.queryReturnOrder(pageData.getParam());
        PageInfo pageInfo = new PageInfo(returnOrderDTOS);
        return new ResponseData<>().ok(pageInfo);
    }

    @Override
    public ResponseData<?> handleReturn(String orderId) { //回单
        //回单 修改回单表状态
        returnOrderMapper.updateStatus(orderId);

        //生成 财务应收单信息
        ReceivableOrder receivableOrder = new ReceivableOrder();
        SnowflakeIdGenerator sg = new SnowflakeIdGenerator();
        String orderNum = String.valueOf(sg.nextId());
        String prefixedOrderNum = "YSD" + orderNum;  //雪花ID
        receivableOrder.setId(prefixedOrderNum);     //单号
        receivableOrder.setOrderId(orderId);         // 订单编号
        //查询订单表信息
        NormalOrder normalOrder = returnOrderMapper.queryById(orderId);
        receivableOrder.setCustomerId(normalOrder.getCustomerId());             //客户表外键
        receivableOrder.setPickupAddressId(normalOrder.getPickupAddressId());        //提货地址
        receivableOrder.setDeliveryAddressId(normalOrder.getDeliveryAddressId());      //收货地址
        ReturnOrder returnOrder = returnOrderMapper.queryByOrderId(orderId);
        receivableOrder.setReturnOrderId(String.valueOf(returnOrder.getId()));          //回单表外键（回单即回款）
        Waybill waybill = returnOrderMapper.queryWayById(normalOrder.getWaybillId());
        receivableOrder.setDriverId(waybill.getDriverManagementId());              //司机外键
        receivableOrder.setSettlementStatus("0");      //结算状态
        receivableOrder.setReconciliationStatus("0");  //对账单状态
        returnOrderMapper.addYingShouDan(receivableOrder);

//        receivableOrder.setFapiaoId();              //发票外键

        //修改订单状态

        return new ResponseData<>().ok();
    }


}
